<template>
  <!-- 登录注册Modal -->
  <div class="modal fade" id="register-modal" data-backdrop="static" data-keyboard="false" tabindex="-1"
       aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-body">
          <!--  注册  -->
          <div class="register-div" v-show="MODAL_STATUS === STATUS_REGISTER">
            <div class="modal-header">
              <h3>注册</h3>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="form-group">
              <input v-model="memberRegister.mobile" class="form-control" placeholder="手机号">
            </div>
            <div class="form-group">
              <div class="input-group">
                <input class="form-control" placeholder="手机验证码">
                <div class="input-group-append">
                  <button @click="sendSmsForRegister()" id="register-btn" class="btn btn-primary btn-block submit-button">
                    发送验证码
                  </button>
                </div>
              </div>
            </div>
            <div class="form-group">
              <input class="form-control" v-model="memberRegister.name" placeholder="昵称">
            </div>
            <div class="form-group">
              <input type="password" v-model="memberRegister.passwordOriginal" class="form-control" placeholder="密码">
            </div>
            <div class="form-group">
              <input type="password" v-model="memberRegister.confirm" class="form-control" placeholder="确认密码">
            </div>
            <div class="form-group">
              <button class="btn btn-primary btn-block submit-button" @click="register()">
                注&nbsp;&nbsp;册
              </button>
            </div>
            <div class="form-group to-login-div">
              <a href="javascript:;" @click="toLoginDiv()">我要登录</a>
            </div>
          </div>

          <!--登录-->
          <div class="login-div" v-show="MODAL_STATUS === STATUS_LOGIN">
            <h3>登&nbsp;&nbsp;录</h3>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <div class="form-group">
              <input v-model="member.mobile" class="form-control" placeholder="手机号">
            </div>
            <div class="form-group">
              <input class="form-control" type="password" placeholder="密码" v-model="member.password">
            </div>
            <div class="form-group">
              <div class="input-group">
                <input id="image-code-input" class="form-control" type="text" placeholder="验证码"
                       v-model="member.imageCode">
                <div class="input-group-addon" id="image-code-addon">
                  <img id="image-code" alt="验证码" v-on:click="loadImageCode()"/>
                </div>
              </div>
            </div>
            <div class="form-group">
              <button v-on:click="login()" class="btn btn-primary btn-block submit-button">
                登&nbsp;&nbsp;录
              </button>
            </div>
            <div class="form-group">
              <div class="checkbox">
                <label>
                  <input type="checkbox" class="remember" v-model="remember"> 记住密码
                </label>
                <div class="pull-right">
                  <a href="javascript:;" v-on:click="toForgetDiv()">忘记密码</a>&nbsp;
                  <a href="javascript:;" v-on:click="toRegisterDiv()">我要注册</a>
                </div>
              </div>
            </div>
            <div class="form-group to-register-div">
            </div>
          </div>

          <!--忘记密码-->
          <div class="forget-div" v-show="MODAL_STATUS === STATUS_FORGET">
            <h3>忘记密码</h3>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
            <div class="form-group">
              <input v-on:blur="onForgetMobileBlur()"
                     v-bind:class="forgetMobileValidateClass"
                     id="forget-mobile" v-model="memberForget.mobile"
                     class="form-control" placeholder="手机号">
              <span v-show="forgetMobileValidate === false" class="text-danger">手机号11位数字，且必须已注册</span>
            </div>
            <div class="form-group">
              <div class="input-group">
                <input v-on:blur="onForgetMobileCodeBlur()"
                       v-bind:class="forgetMobileCodeValidateClass"
                       id="forget-mobile-code" class="form-control"
                       placeholder="手机验证码" v-model="memberForget.smsCode">
                <div class="input-group-append">
                  <button v-on:click="sendSmsForForget()"
                          class="btn btn-outline-secondary" id="forget-send-code-btn">
                    发送验证码
                  </button>
                </div>
              </div>
              <span v-show="forgetMobileCodeValidate === false" class="text-danger">请输入短信6位验证码</span>
            </div>
            <div class="form-group">
              <input v-on:blur="onForgetPasswordBlur()"
                     v-bind:class="forgetPasswordValidateClass"
                     id="forget-password" v-model="memberForget.passwordOriginal"
                     class="form-control" placeholder="密码" type="password">
              <span v-show="forgetPasswordValidate === false" class="text-danger">密码最少6位，包含至少1字母和1个数字</span>
            </div>
            <div class="form-group">
              <input v-on:blur="onForgetConfirmPasswordBlur()"
                     v-bind:class="forgetConfirmPasswordValidateClass"
                     id="forget-confirm-password" v-model="memberForget.confirm"
                     class="form-control" placeholder="确认密码" type="password">
              <span v-show="forgetConfirmPasswordValidate === false" class="text-danger">确认密码和密码一致</span>
            </div>
            <div class="form-group">
              <button v-on:click="resetPassword()" class="btn btn-primary btn-block submit-button">
                重&nbsp;&nbsp;置
              </button>
            </div>
            <div class="form-group to-login-div">
              <a href="javascript:;" v-on:click="toLoginDiv()">我要登录</a>
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import {onMounted, ref} from "vue";
import axios from "axios";

export default {
  name: "login",
  emits: ['setLoginMember'],
  setup(props, { emit }) {
    const memberRegister = ref({}); // 注册对象
    const member = ref({}); // 登录对象
    const memberForget = ref({}); // 忘记密码对象
    // 模态框内容切换：登录、注册、忘记密码
    let STATUS_LOGIN = ref("STATUS_LOGIN");
    let STATUS_REGISTER = ref("STATUS_REGISTER");
    let STATUS_FORGET = ref("STATUS_FORGET");
    let MODAL_STATUS = ref(""); // 当前框
    let imageCodeToken = ref(); // 图片验证码token
    const remember = ref(true); // 记住我
    let countDown;// 验证码倒计时60s

    /**
     * 打开模态框
     */
    const openRegisterMember = () => {
      // 清空注册对象
      memberRegister.value = {};
      $('#register-modal').modal('show')
    }

    /**
     * 注册
     */
    const register = () => {
      // 密码加密
      memberRegister.value.password = hex_md5(memberRegister.value.passwordOriginal + KEY);
      // 调服务端注册接口
      axios.post(process.env.VUE_APP_SERVER + '/business/web/member/register', memberRegister.value).then((response) => {
        let resp = response.data;
        if (resp.success) {
          Toast.success("注册成功");
          $('#register-modal').modal('hide'); // 关闭模态框
        } else {
          Toast.warning(resp.message);
        }
      })
    }

    /**
     * 登录
     */
    const login = () => {
      let md5= hex_md5(member.value.password + KEY);
      member.value.imageCodeToken = imageCodeToken.value;
      let rememberMember = LocalStorage.get(LOCAL_KEY_REMEMBER_MEMBER) || {};
      if (md5 != rememberMember.md5) {  // 看看密码有没有改变
        member.value.password = hex_md5(member.value.password + KEY);
      }

      axios.post(process.env.VUE_APP_SERVER + '/business/web/member/login', member.value).then((response) => {
        let resp = response.data;
        if (resp.success) {
          Toast.success("登录成功");
          $('#register-modal').modal('hide'); // 关闭模态框
          Tool.setLoginMember(resp.content);
          // 完成记住我
          if (remember.value) {
            // 记住我
            let md5 = hex_md5(member.value.password + KEY);
            LocalStorage.set(LOCAL_KEY_REMEMBER_MEMBER, {
              mobile: member.value.mobile,
              md5: md5,
              password: member.value.password,
            });
          } else {
            // 本地缓存清空
            LocalStorage.remove(LOCAL_KEY_REMEMBER_MEMBER, null);
          }
        } else {
          Toast.warning(resp.message);
        }
        // 通知父组件
        emit('setLoginMember');
      })
    }

    /**
     * 图片验证码
     */
    const loadImageCode = () => {
      imageCodeToken.value = Tool.uuid(8);
      $('#image-code').attr('src', process.env.VUE_APP_SERVER + '/system/web/kaptcha/image-code/' + imageCodeToken.value);
    }

    //---------------登录框、注册框、忘记密码框切换-----------------
    const toLoginDiv = () => {
      loadImageCode(); // 加载验证码
      member.value = {}; // 清空登录对象
      // 加载记住的用户
      let rememberMember = LocalStorage.get(LOCAL_KEY_REMEMBER_MEMBER);
      if (rememberMember) {
        member.value = rememberMember;
      }

      MODAL_STATUS.value = STATUS_LOGIN.value
    }
    
    const toRegisterDiv = ()=> {
      MODAL_STATUS.value = STATUS_REGISTER.value
    }
    
    const toForgetDiv = ()=> {
      MODAL_STATUS.value = STATUS_FORGET.value
    }

    /**
     * 注册验证码
     */
    const sendSmsForRegister = () => {
      let sms = {
        mobile: memberRegister.value.mobile,
        use: SMS_USE.REGISTER.key
      };
      axios.get(process.env.VUE_APP_SERVER + '/business/web/sms/find-mobile/' + memberRegister.value.mobile).then((response) => {
        let resp = response.data;
        if (resp.success) {
          Toast.warning("手机号已注册");
        } else {
          sendSmsCode(sms, "register-btn");
        }
      })
    }

    /**
     * 发送验证码
     * 把按钮disabled
     */
    const sendSmsCode = (sms, btnId) => {
      axios.post(process.env.VUE_APP_SERVER + '/business/web/sms/send', sms).then((response) => {
          if (response.data.success) {
            Toast.success("短信验证码发送成功");
            // 设置获取时间
            countDown = 60; // 配置倒计时60s
            setTime(btnId);
          } else {
            Toast.error(response.data.message);
          }
      })
    }

    /**
     * 渲染验证码倒计时
     * 定时器设置倒计时
     */
    const setTime = (btnId) => {
      let btn = $("#" + btnId);
      if (countDown === 0) {
        btn.removeAttr("disabled");
        btn.text("获取验证码");
        return;
      } else {
        btn.attr("disabled", true);
        countDown--;
        btn.text("倒计时（" + countDown + ")秒");
      }
      setTimeout(()=> {
        setTime(btnId);
      }, 1000)
    }

    onMounted(() => {
      toLoginDiv();
    })

    return {
      openRegisterMember,
      memberRegister,
      register,
      STATUS_LOGIN,
      STATUS_REGISTER,
      STATUS_FORGET,
      MODAL_STATUS,
      toLoginDiv,
      toRegisterDiv,
      toForgetDiv,
      member,
      memberForget,
      loadImageCode,
      login,
      remember,
      sendSmsForRegister
     }
  }
}
</script>

<style scoped>
#register-modal h3 {
  text-align: center;
}

#register-modal .to-login-div {
  text-align: center;
}

#login-modal .submit-button {
  height: 50px;
  font-size: 20px;
}

</style>